/**
 * =============================================
 * 自定义项目api统一导入插件
 * 创作者：学答也
 * 创建日期：2025-11-13
 * 联系方式：2304493354@qq.com
 * =============================================
 */
import { resolve } from 'path';
import * as fs from 'fs';
import * as eslexer from 'es-module-lexer';
import { parse } from 'recast';

export interface AutoApiOptions {
	/** api目录相对项目根目录的路径，默认 src/api */
	dir ?: string;
}

export default function autoApiHMR(options : AutoApiOptions = {}) {
	const apiDir = resolve(process.cwd(), options.dir || 'src/api');
	const indexPath = resolve(apiDir, 'index.js');
	/** 获取真正的 API文件列表（不含 index） */
	function listApiFiles() : string[] {
		if (!fs.existsSync(apiDir)) return [];
		return fs.readdirSync(apiDir).filter(
			f =>
				/\.(m?j|t)sx?$/.test(f) && f !== 'index.js' && f !== 'index.ts'
		);
	}

	async function genIndex() {
		await eslexer.init;
		const allJs = listApiFiles()
		// 如果只有一个index.js文件，则拦截
		if (allJs.length <= 1 && allJs.includes('index.js')) return;

		const files = allJs.filter(f => f !== 'index.js');

		const imports : string[] = [];
		const apis : string[] = [];
		for (const file of files) {
			const modId = file.replace('.js', '');
			const code = fs.readFileSync(resolve(apiDir, file), 'utf-8');
			const [, exports] = eslexer.parse(code);
			if (!exports.length || exports[0].n !== 'default') continue;

			const ast = parse(code);
			const defNode = ast.program.body.find(
				(n : any) => n.type === 'ExportDefaultDeclaration'
			);
			if (defNode?.declaration.type === 'ObjectExpression') {
				defNode.declaration.properties.forEach((p : any) => {
					console.log(p.key.name, 'p.type', p.type);
					// if (p.type === 'ObjectProperty' && p.key.name) {
					apis.push(`${p.key.name}:  ${modId}.${p.key.name}`);
					// }
				});
			}
			imports.push(`import  ${modId} from './${modId}';`);
		}

		const content = `const files = import.meta.glob('./*.js', {eager: true});
${imports.join('\n')} 
let api = {
${apis.map(a => `  ${a}`).join(',\n')}
};
Object.keys(files).forEach((key) => {
	api = {
		...api,
		// [key.replace(/(.*\/)*([^.]+).*/gi, '$2')]: files[key].default,
		...files[key].default
	};
});
export default api;
`;
		fs.writeFileSync(indexPath, content, 'utf-8');
	}

	return {
		name: 'auto-api-hmr',
		apply: 'serve',
		configureServer(server) {
			if (listApiFiles().length === 0) return;
			genIndex();
			server.watcher.add(apiDir);
			server.watcher.on('add', onChange);
			server.watcher.on('change', onChange);
			server.watcher.on('unlink', onChange);

			function onChange(file : string) {
				if (!file.endsWith('.js')) return;
				genIndex();
				server.moduleGraph.fileToModulesMap.get(indexPath)?.forEach(m => server.reloadModule(m));
			}
		},
		/** ←同时支持 build  */
		buildStart() {
			if (listApiFiles().length === 0) return;
			genIndex();
		}
	};
}